﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <head>
        <title></title>
        <link rel="stylesheet" type="text/css" href="/lib/css/layout-default-latest.css" />
        <link rel="stylesheet" type="text/css" href="/lib/css/themes/base/jquery.ui.all.css" />
        <link href="/lib/css/StyleSheet1.css" rel="stylesheet" type="text/css" />
        <link rel="stylesheet" href="/plugins/slick.grid.css" type="text/css" />
        <link rel="stylesheet" href="/lib/css/jquery.jdMenu.css" type="text/css" />
        <link href="/plugins/CheckList/ui.dropdownchecklist.themeroller.css" rel="stylesheet" />
        <style type="text/css">
            /* remove padding and scrolling from elements that contain an Accordion OR a content-div */
            .ui-layout-center, /* has content-div */ .ui-layout-west, /* has Accordion */ .ui-layout-east, /* has content-div ... */ .ui-layout-east .ui-layout-content
            {
                /* content-div has Accordion */
                padding: 0;
                overflow: hidden;
            }
            .ui-layout-center P.ui-layout-content
            {
                line-height: 1.4em;
                margin: 0; /* remove top/bottom margins from <P> used as content-div */
            }
            h3, h4
            {
                /* Headers & Footer in Center & East panes */
                font-size: 1.1em;
                background: #EEF;
                border: 1px solid #BBB;
                border-width: 0 0 1px;
                padding: 7px 10px;
                margin: 0;
            }
            .ui-layout-east h4
            {
                /* Footer in East-pane */
                font-size: 0.9em;
                font-weight: normal;
                border-width: 1px 0 0;
            }
            .menuContainerJSListBox
            {
                margin-left: 50px;
                margin-right: 50px;
                margin-bottom: 50px;
                overflow: auto;
            }
            .DCTextClass
            {
                margin-top: 10px;
                margin-left: 50px;
                margin-right: 50px;
                margin-bottom: 20px;
            }
            .NDPriceCss
            {
            
            }
            #loadingScreen
            {
                background: url(../images/ajax-loader.gif) no-repeat 5px 8px;
                padding-left: 25px;
            }
            .loadingScreenWindow .ui-dialog-titlebar-close
            {
                display: none;
            }
            .highlightPriceApporver
            {
                background-color: white;
                border: 1px solid black;
            }
            .highlightPriceApporver1
            {
                background-color: #1bbe46;
                height: 23px;
            }
            .highlightPriceApporver2
            {
                background-color: Orange;
                height: 23px;
            }
        
            .highlightPriceApporver3
            {
                background-color: #FF3300;
                height: 23px;
            }
        </style>
        <!-- REQUIRED scripts for layout widget -->
        <script src="/lib/js/jquery-latest.js" type="text/javascript"></script>
        <script src="/lib/js/jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="/lib/js/jquery.layout-latest.js"></script>
        <script type="text/javascript" src="/lib/js/jquery.layout.resizePaneAccordions-1.0.js"></script>
        <script src="/plugins/globalize.js" type="text/javascript"></script>
        <script type="text/javascript" src="/lib/js/themeswitchertool.js"></script>
        <script type="text/javascript" src="/lib/js/debug.js"></script>
        <script type="text/javascript" src="/lib/js/jquery.dimensions.js"></script>
        <script type="text/javascript" src="/lib/js/jquery.positionBy.js"></script>
        <script type="text/javascript" src="/lib/js/jquery.bgiframe.js"></script>
        <script type="text/javascript" src="/lib/js/jquery.jdMenu.js"></script>
        <script src="/lib/js/jquery.event.drag-2.0.min.js"></script>
        <script src="/plugins/slick.editors.js"></script>
        <script src="/plugins/slick.core.js"></script>
        <script src="/plugins/slick.checkboxselectcolumn.js"></script>
        <script src="/plugins/slick.autotooltips.js"></script>
        <script src="/plugins/slick.cellrangedecorator.js"></script>
        <script src="/plugins/slick.cellrangeselector.js"></script>
        <script src="/plugins/slick.cellcopymanager.js"></script>
        <script src="/plugins/slick.cellselectionmodel.js"></script>
        <script src="/plugins/slick.rowselectionmodel.js"></script>
        <script src="/plugins/slick.formatters.js"></script>
        <script src="/plugins/slick.grid.js"></script>
        <script src="/Scripts/Helper.js" type="text/javascript"></script>
        <script src="/Scripts/AjaxLoading.js" type="text/javascript"></script>
        <script src="/plugins/surge.core.js" type="text/javascript"></script>
        <script src="/plugins/surge.slickGrid.js" type="text/javascript"></script>
        <script src="/plugins/ListView/js-inherit.js" type="text/javascript"></script>
        <script src="/plugins/ListView/js-listbox.js" type="text/javascript"></script>
        <script src="/plugins/CheckList/ui.dropdownchecklist.js" type="text/javascript"></script>
        <script src="/Scripts/CurrentTime.js" type="text/javascript"></script>
        <script type="text/javascript">
            window.onload = DisplayTime;
            var myLayout;
            var helper = new Helper();
            var approverAll = [];
            $(document).ready(function () {
                var rolename = $.cookie("userrole");
                if (rolename == null || rolename != 'Admin') {
                    window.location = '/Page/login.aspx';
                }
                //loadFrm("/page/userManagement.htm");

                myLayout = $('body').layout({
                    west__size: 234
                    , east__size: 300
                    // RESIZE Accordion widget when panes resize
                    , west__onresize: $.layout.callbacks.resizePaneAccordions
                    , east__onresize: $.layout.callbacks.resizePaneAccordions
                    , west__initClosed:true
                });

                $('ul.dropdown').jdMenu();
                // ACCORDION - in the West pane
                $("#accordion1").accordion({ fillSpace: true });

                // ACCORDION - in the East pane - in a 'content-div'
                $("#accordion2").accordion({
                    fillSpace: true
                    , active: 1
                });


                // THEME SWITCHER
                addThemeSwitcher('.ui-layout-north', { top: '12px', right: '5px' });
                // if a new theme is applied, it could change the height of some content,
                // so call resizeAll to 'correct' any header/footer heights affected
                // NOTE: this is only necessary because we are changing CSS *AFTER LOADING* using themeSwitcher
                setTimeout(myLayout.resizeAll, 1000); /* allow time for browser to re-render with new theme */

                $("#sapExportTextDownload").dialog({
                    autoOpen: false,
                    resizable: true,
                    height:280,
                    width:250,
                    dialogClass: "Dialog",
                    title: "SAP text files download",
                    modal: false,
                    buttons: {
                        Ok: function() {
                            $("#sapExportTextDownload").dialog("close");
                            document.location.reload(true);
                        }
                    }
                });
                $("#sapExportNDTextDownload").dialog({
                    autoOpen: false,
                    resizable: false,
                    height:200,
                    width:250,
                    dialogClass: "Dialog",
                    title: "SAP text files download",
                    modal: false,
                    buttons: {
                        Ok: function() {
                            $("#sapExportNDTextDownload").dialog("close");
				        
                        }
                    }
                });
                $("#dialog-confirm" ).dialog({
                    autoOpen: false,
                    resizable: false,
                    height:150,
                    dialogClass: "Dialog",
                    modal: true,
                    buttons: {
                        "Delete all items": function() {
                            var selectedDoc = new Array();
			                
                            var selectRow = documentgrids[activeTab].getSelectedRows();
                            jQuery.each(selectRow, function (index, value) {
                                selectedDoc.push(documentgrids[activeTab].getData()[value]["DocID"]);
                            });
                            //var docData = { DocID: documentid, Status: status  };
                            helper.DeleteDocs(selectedDoc, function(data) {
                                MsgBox('Deleted ' + data +' document Success');
                                $("#dialog-confirm").dialog("close");
                                window.location.reload(true);
                            });
					
                        },
                        Cancel: function() {
                            $( this ).dialog("close");
                        }
                    }
                });
                $("#DivNdpriceDetails").dialog({
                    autoOpen: false,
                    resizable: false,
                    title: "ND Price",
                    dialogClass: "Dialog",
                    width:500,
                    modal: true,
                    buttons: {
			    
                        Ok: function() {
                            $("#DivNdpriceDetails").dialog("close");
                        },
                        ExportSapND :function () {
                            helper.ExportSaPNDfile(RoundID, function(data) {
                                var contentSAPdownload = '';
                                if (data) {
                                    $.each(data, function(key, value) {
                                        contentSAPdownload += '<a type="file" target="_blank" href="' + value.FilePath + '">' + 'Text File '+ value.DocType  + '</a>';
                                        contentSAPdownload += '<br/>';
                                        contentSAPdownload += '<br/>';
                                    });
                                    $('#sapExportNDTextDownloadContent').html(contentSAPdownload);
                                    $("#sapExportNDTextDownload").dialog('open');
                                    var top = ($(window).height() - 200) / 2;
                                    var left = ($(window).width() - 350) / 2;

                                    $(".Dialog").css('left', left);
                                    $(".Dialog").css('top', top);
                                }
                            });
                        }
				
                    }
                });
                showLayout('1');
            
                $("#bthQuickSearchDoc").button({
                 
                    icons: {
                        primary: "ui-icon-search"
                    }
                })
                    .click(function () {
                        searchDocument();
                    });
                helper.GetAllApproveLevel(function(approval) {
                    approverAll = approval;
                    $.each(approverAll.AllApprover, function(i, v) {
                        if (i == 0) {
                            $('head').append("<style>.highlightPriceApporve { background-color:" + v.warningColor +" }</style>");
                            $('#approvalDisplay').text(v.approveDisplay);
                        }
                        else if (i== 3) {
                            $('#approvalDisplay' + i).text(v.approveDisplay);
                        } else {
                            $('head').append("<style>.highlightPriceApporver" + i +" { background-color:" + v.warningColor +" }</style>");
                            $('#approvalDisplay' + i).text(v.approveDisplay);  
                        }
                     
                    
                    });
                });

            });
            var discountgrid;
            var documentid;
            var allDocuments;
            var allTab;
//        function saveAs(a){
//            document.getElementById('ifr').setAttribute('src',a);
//            z = top.frames[0].location.href.split('/');
//            zz = z[z.length-1];
//            if(zz == a){top.frames[0].document.execCommand('SaveAs');clearTimeout(y)}
//            else{y = setTimeout('saveAs(\''+a+'\')',1)}
//        }
            var activeTab = 'all';
            function showLayout(step, docid,doctype) {
                switch (step) {
                case '1':
                    $('#mainFrame').html($('#DocumentListAdminStep').html());
                    $("#btnExportSAP")
                        .button({
                 
                            icons: {
                                primary: "ui-icon-plusthick"
                            },  
                        })
                        .click(function () {
                            //var selectApproveGrid = $("#grid10");
			                
                            var selectedDoc = [];
                            var test = documentgrids['10'].getSelectedRows();
                            jQuery.each(test, function (index, value) {
                                selectedDoc.push(documentgrids['10'].getData()[value]["DocID"]);
                            });
                            var selectRow40 = documentgrids['40'].getSelectedRows();
                            jQuery.each(selectRow40, function (index, value) {
                                selectedDoc.push(documentgrids['40'].getData()[value]["DocID"]);
                            });
                            helper.ExportSaPfile(selectedDoc, function(data) {
                                var contentSAPdownload = '';
                                if (data) {
                                    $.each(data, function(key, value) {
                                        contentSAPdownload += '<a type="file" target="_blank" href="' + value.FilePath + '">' + 'Text File '+ value.DocType  + ' Level ' + value.DociD + '</a>';
                                        contentSAPdownload += '<br/>';
                                        contentSAPdownload += '<br/>';
                                    });
                                    $('#sapExportTextDownloadContent').html(contentSAPdownload);
                                    $("#sapExportTextDownload").dialog('open');
                                    var top = ($(window).height() - 280) / 2;
                                    var left = ($(window).width() - 350) / 2;

                                    $(".Dialog").css('left', left);
                                    $(".Dialog").css('top', top);
                                }
                            });
                        });
                    
                    $("#btnConfirmUploadedSAP")
                        .button({
                 
                            icons: {
                                primary: "ui-icon-plusthick"
                            },  
                        })
                        .click(function () {
                            //var selectApproveGrid = $("#grid10");
			                
                            var selectedDoc = new Array();
			                
                            var selectRow40 = documentgrids['40'].getSelectedRows();
                            jQuery.each(selectRow40, function (index, value) {
                                selectedDoc.push({DocID: documentgrids['40'].getData()[value]["DocID"] , Status: 50});
                            });
                            //var docData = { DocID: documentid, Status: status  };
                            helper.UpdateListDocumentStatus(selectedDoc, function(data) {
                                MsgBox('Update ' + data +' document Success');
                                showLayout('1');
                            });
                        });

                    $("#btnDeleteDoc")
                        .button({
                 
                            icons: {
                                primary: "ui-icon-plusthick"
                            },  
                        })
                        .click(function () {
                            if (documentgrids[activeTab].getSelectedRows().length > 0)
                            {
                                var top = ($(window).height() - 150) / 2;
                                var left = ($(window).width() - 350) / 2;
                                $("#dialog-confirm").dialog("open");
                                $(".Dialog").css('left', left);
                                $(".Dialog").css('top', top);
                            }
                        });
                    var tabHtmlComplete = '';
                    var divHtmlComplate = '';
                    var tabItemHtml = '<ul>{0}<ul>';
                    var tabItemComplete = '';
                    var constTabID = '';
                    var constGrid = 'grid';
                    var constAllstatus = 'all';
                    helper.GetStatusTab(function (allTabStatus){
                        allTab = allTabStatus.AllStatus;
                        var htmltemplate = '<li><a href="#{0}">{1}</a></li>';
                        tabItemComplete += htmltemplate.format(constTabID + constAllstatus,'ALL'); // add tab All
                        $.each(allTabStatus.AllStatus, function(key, value) {
                            tabItemComplete += htmltemplate.format(constTabID + value.StatusID, value.StatusDescription);

                        });
                        tabHtmlComplete = tabItemHtml.format(tabItemComplete);
                        var divTemplate = '<div id="{0}"><div></div><div style="height:300px; padding-bottom:10px;" id="{1}">{0} </div></div>';
                        divHtmlComplate += divTemplate.format(constTabID + constAllstatus, constGrid+ constAllstatus); // add div grid all
                        $.each(allTabStatus.AllStatus, function(key, value) {
                            divHtmlComplate += divTemplate.format(constTabID + value.StatusID, constGrid+ value.StatusID);

                        });
                    
                        $("#tabs").html(tabHtmlComplete).append(divHtmlComplate);

                        helper.GetDocumentByAdmin(function (alldocument){
                            allDocuments = alldocument.AllDocument;
                            GridDocumentInit('#' + constGrid+ constAllstatus ,alldocument.AllDocument,constAllstatus);
                            $.each(allTabStatus.AllStatus, function(key, value) {
                                GridDocumentInit('#' + constGrid+ value.StatusID ,alldocument.AllDocument,value.StatusID);
                            });
                            //GridDocumentInit('#grid11' ,alldocument.AllDocument,'11');
                        });

                    
                        $( "#tabs").tabs({
                                select: function(event, ui) {
                                    var tabname = ui.panel.id;
                                    activeTab = ui.panel.id;
                                    if (tabname == '10' || tabname == '40') {
                                        $('#btnExportSAP').show();
                                    }
                                    else {
                                        $('#btnExportSAP').hide();
                                    }
                                    if (tabname == '40') {
                                        $('#btnConfirmUploadedSAP').show();
                                    }
                                    else {
                                        $('#btnConfirmUploadedSAP').hide();
                                    }
                                },
                                selected: 2
                            }
                        );
                        // set default active tab to approved status's tab
                        activeTab = '10'; 
                        $('#btnExportSAP').show();
                            
                    });
                    break;

                case '3':
                    $('#mainFrame').html($('#DocumentDetailAdminStep').html());
                    
              
                    if (docid){
                        documentid = docid;
                        $("#txtDocID").text(docid);
                        var docDetail = jQuery.grep(allDocuments, function(n, i){
                            return (n.DocID === documentid);
                        });
                        $.each(docDetail, function(key,value) {
                            $('#txtValidOn').val(value.ValidON);
                            $('#txtValidTo').val(value.ValidTO);
                            $('#txtSaleName').val(value.msalerep_name);
                            $('#txtSaleGroup').val(value.msalegrp_desc);
                            $('#remark').val(value.Remark);
                            $('#remark2').val(value.Remark2);
                            if (value.Status != '10') {
                                $('#divButton').hide();
                            }
                            else {
                                $("#txtValidOn").datepicker({dateFormat: 'yy-mm-dd'});
                                //var today = new Date();
                                //$("#txtValidOn").datepicker("option", "minDate", today );
                                $("#txtValidTo").datepicker({dateFormat: 'yy-mm-dd'});
                                $("#txtValidOn").change(function() {
                                    var test = $(this).datepicker('getDate');
                                    $("#txtValidTo").datepicker("option", "minDate", test );
                                });
                            }
                        });
                        var optionsProductGridReadOnly = {
                            editable: true,
                            enableRowReordering: true,
                            enableCellNavigation: true,
                            asyncEditorLoading: false,
                            autoEdit: false
                        };
                        //Init Print button only status uploaded to sap
                        
                        var data = jQuery.grep(allDocuments, function(n, i){
                            return (n.DocID === docid);
                        });
                        if (data.length > 0) {
                            if (data[0].Status == "50") {
                    
                                $("#btnPrint").show();
                                $("#btnPrint")
                                    .button({                 
                                        icons: {
                                            primary: "ui-icon-plus"
                                        },
                            
                                    })
                                    .click(function() {
                                        window.open('/Page/ReportViewer.aspx?docid=' + docid + '&doctype=' + doctype);

                                    });
                            }
                        }

                        helper.GetColumnDocumentDetailByDocID(docid,doctype, function (columns) {
                            var cs = [];
                            cs.push({ id: "ProductDesc", name: "", field: "ProductDesc", minWidth: 60 });
                            cs.push({ id: "NDPrice", name: "NDPrice", field: "NDPrice", minWidth: 5, width: 60, cssClass: 'NDPriceCss' });

                            $.each(columns.allColumns, function (key, value) {
                                if (value.ParentText != undefined && value.ParentText != null) {
                                    cs.push({ parentable: 1, id: value.RefID, dc: value.DCID, name: '(DC ' + value.DCID + ') ' + value.mcustname1 + "(" + value.ParentText + ")", field: value.RefID, minWidth: 60, width: 150, formatter: Slick.Formatters.DisableSupport, toolTip: value.ParentText });
                                }
                                else {
                                    cs.push({ parentable: 1, id: value.RefID, dc: value.DCID, name: '(DC ' + value.DCID + ') ' + value.mcustname1 , field: value.RefID, minWidth: 60, width: 150, formatter: Slick.Formatters.DisableSupport, toolTip: value.ParentText });
                                }
                            });

                            helper.GetDocumentDetailByDocID(docid, false, function(datas) {
                                var d =[];
                                helper.GetProductToSaleDocid(docid,function(data) {
                                    $.each(data.AllProduct, function (key, value) {
                                        $.each(datas.AllDocumentDetail, function(key2, value2) {
                                            var item = value2;
                                            if (value.mprodh_grpname === value2.ProductDesc) {
                                                item.NDPriceApprove1 = value.NDApproverLevel1;
                                                item.NDPriceApprove2 = value.NDApproverLevel2;
                                                item.NDPriceApprove3 = value.NDApproverLevel3;
                                                d.push(item);
                                            }
                                            
                                        });
                                    });
                                });
                                
                                //sortJsonArrayByProp(d, "sort")();
                                RefreshGridDiscount(d, cs, optionsProductGridReadOnly);
                            });
                        });
                    }
//                    $("#btnEdit")
//                        .button({

//                                icons: {
//                                    primary: "ui-icon-circle-check"
//                                },
//                            })
//                        .click(function() {
//                            var doctype = '01';
//                            var status = '10';
//                            var remark2 = $('#remark2').val();
//                            var docData = { DocID: documentid, DocType:doctype, Status: status, Remark2: remark2 };
//                            helper.UpdateDocumentStatus(docData, function(data) {
//                                MsgBox('Approved ' + data +' document Success');
//                                showLayout('1');
//                            });
//                        });
                    $("#btnSave")
                        .button({

                            icons: {
                                primary: "ui-icon-circle-close"
                            },
                        })
                        .click(function() {
                            var status = '51';
                            var remark = $('#remark').val();
                            var remark2 = $('#remark2').val();
//                            var validon = $.datepicker.formatDate('yy-mm-dd', $('#txtValidOn').datepicker('getDate'));
//			    
//			                var validto = $.datepicker.formatDate('yy-mm-dd', $('#txtValidTo').datepicker('getDate'));
                            var validon =$('#txtValidOn').val();
			    
                            var validto =$('#txtValidTo').val();
                            var docData = { DocID: documentid,
                                DocType:doctype,
                                Remark: remark,
                                Remark2: remark2,
                                ValidOn: validon,
                                ValidTo: validto,
                                Status: status
                            };
                            helper.UpdateDocumentStatus(docData, function(data) {
                                MsgBox('Saved ' + data + ' document Success');
                                window.location.reload(true);
                                //showLayout('1');
                            });
                        });
                    
                    $("#btnBackToDocList")
                        .button({

                            icons: {
                                primary: "ui-icon-circle-arrow-w"
                            },
                        })
                        .click(function() {
                            
                            window.location.reload(true);
                        });
                     
                    break;
                }
            }
            function searchDocument(key) {
                if (key == 13) {
                    event.cancelBubble = true;
                    return false;
                }
                var searchText = $("#txtQuickFilterDoc").val();
                var filterDocs = jQuery.grep(allDocuments, function(element, index){
                    return element.DocID.toLowerCase().indexOf(searchText.toLowerCase()) != -1 || element.UserName.toLowerCase().indexOf(searchText.toLowerCase()) != -1; 
                });

                var constGrid = 'grid';
                var constAllstatus = 'all';
                documentgrids[constAllstatus].setData(filterDocs);
                documentgrids[constAllstatus].render();
                $.each(allTab, function(key, value) {
                    var datas;
                    datas = jQuery.grep(filterDocs, function(n, i) {
                        return (n.Status === value.StatusID);
                    });
                    documentgrids[value.StatusID].setData(datas);
                    documentgrids[value.StatusID].render();
                    //GridDocumentInit('#' + constGrid+ value.StatusID ,filterDocs,value.StatusID);
                });
           
            }

            var approveLevel = 0;
            function RefreshGridDiscount(datas, cs, options) {

                discountgrid = new Slick.Grid("#SaleCustomerDetailGrid", datas, cs, options);
                discountgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));

                discountgrid.onBeforeEditCell.subscribe(function(e, args) {
                    var value = datas[args.row][discountgrid.getColumns()[args.cell].field];
                    if (value === 'N/A') {
                        return false;
                    } else {
                        return true;
                    }

                });
                $('#realApprove').text(getRealApproval(datas,cs));

                discountgrid.onCellChange.subscribe(function(e,args) {
              
                    $('#realApprove').text(getRealApproval()); 
                });
           
            }
            function findColumnIndex(cs, columnName) {
                for (var i = 0; i < cs.length; i++) {
                    if(cs[i].field === columnName ) {
                        return i;
                    }
                }
            }
            function getRealApproval(datas, cs) {
                if (datas === undefined) {
                    datas = discountgrid.getData();
                    cs = discountgrid.getColumns();
                }
                approveLevel = 0;
                $.each(cs, function (name, value) {
                    var custId = value.id;
                    if (value.dc != undefined) {
                        for (var v in datas) {
                            if (datas[v][custId] != 'N/A') {
                                var currentInputValue = datas[v].NDPrice - datas[v][custId];
                                if (currentInputValue <= datas[v].NDPriceApprove1) {
                                    $('#approveLevelDetails').show();
                                }
                                else if (currentInputValue > datas[v].NDPriceApprove1 && currentInputValue <= datas[v].NDPriceApprove2) {
                                    if (approveLevel < 1) {
                                        approveLevel = 1;
                                        $('#approveLevelDetails').show();
                                    }
                                }
                                else if (currentInputValue > datas[v].NDPriceApprove2 && currentInputValue <= datas[v].NDPriceApprove3) {
                                    if (approveLevel < 2) {
                                        approveLevel = 2;
                                        $('#approveLevelDetails').show();
                                    }
                                }
                                else if (currentInputValue > datas[v].NDPriceApprove3) {
                                    if (approveLevel < 3) {
                                        approveLevel = 3;
                                        $('#approveLevelDetails').show();
                                    }
                                }
                            }
                        };
                    }
                });
                var approvalDisaplay ="";
                helper.GetAllApproveLevel(function(approval) {
                    approverAll = approval;
                    $.each(approverAll.AllApprover, function(i, v) {
                        if (i == 0) {
                            $('head').append("<style>.highlightPriceApporve { background-color:" + v.warningColor +" }</style>");
                        }
                        else if (i== 3) {

                        } else {
                            $('head').append("<style>.highlightPriceApporver" + i +" { background-color:" + v.warningColor +" }</style>");
                        }
                    });
                });
                return approvalDisaplay;
            }
            function loadFrm(url){

                $.get(url, function(content){

                    $('#mainFrame').html(content);   

                });
            }
            function MsgBox(message) {
                $('#MessageBar').html(message);
            }
            function GridDocumentListApprovalStepInit(gridtarget, allDocument, searchText) {
                var columnGridDocument = [
                    { id: "DocID", name: "Document ID", field: "DocID", width: 120, cssClass: "cell-title" },
                    { id: "Region", name: "Region", field: "Region" },
                    { id: "CreateBy", name: "CreateBy", field: "UserName", width: 80, resizable: false },
                    { id: "CreateOn", name: "CreateOn", field: "Created", minWidth: 60 },
                    { id: "Enter", name: "", field: "DocID", formatter: Slick.Formatters.Enter },
                ];
                var optionsDocumentGrid = {
                    editable: false,
                    enableRowReordering: true,
                    enableCellNavigation: true,
                    asyncEditorLoading: false,
                    autoEdit: false
                };

                if (searchText === 'all') {
                    allDocument = allDocument;
                } 
                else {
                    allDocument = jQuery.grep(allDocument, function (n, i) {
                        return (n.Status.indexOf(searchText) >= 0);
                    });
                }
                var documentgrid = new Slick.Grid(gridtarget, allDocument, columnGridDocument, optionsDocumentGrid);
                documentgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
            }
        
            function GridDocumentInit(gridtarget,allDocument, status) {
                var columnGridDocument = [
                    { id: "StatusDescription", name: "สถานะ", field: "StatusDescription", width: 120, cssClass: "cell-title" },
                    { id: "DocID", name: "Document ID", field: "DocID", width: 120 },
                    { id: "DocType", name: "Document Type ", field: "Doctype", width: 120, formatter: Slick.Formatters.DocType },
                    { id: "Region", name: "Region", field: "Region" },
                    { id: "CreateBy", name: "CreateBy", field: "UserName", width: 80, resizable: false },
                    { id: "CreateOn", name: "CreateOn", field: "Created", minWidth: 60 },
                    { id: "Enter", name: "", field: "DocID", formatter: Slick.Formatters.Enter },
                ];
                var optionsDocumentGrid = {
                    editable: true,
                    enableRowReordering: true,
                    enableCellNavigation: true,
                    asyncEditorLoading: false,
                    autoEdit: false
                };
                var checkboxSelector = new Slick.CheckboxSelectColumn({
                    cssClass: "slick-cell-checkboxsel"
                });
                columnGridDocument.splice(0, 0, checkboxSelector.getColumnDefinition());
                var datas = [];
                var documentgrid;
                if (status === 'all') {
                    datas = allDocument;
                    documentgrid = new Slick.Grid(gridtarget, datas, columnGridDocument, optionsDocumentGrid);
                    documentgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
                    documentgrid.registerPlugin(checkboxSelector);
                    documentgrid.onCellChange.subscribe(function(e, args) {
                        //updateUser(args.item);
                    });
                }
                else if (status === '51') {
                    datas = jQuery.grep(allDocument, function(n, i){
                        return (n.isedited === true);
                    });
                    documentgrid = new Slick.Grid(gridtarget, datas, columnGridDocument, optionsDocumentGrid);
                    documentgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
                    documentgrid.registerPlugin(checkboxSelector);
                    documentgrid.onCellChange.subscribe(function(e, args) {
                        //updateUser(args.item);
                    });
                }
                else if (status === '99') {
                    helper.getAllNdPrice(function(allNdPrice) {
                        datas = allNdPrice.RNdPrice;
                        var columnGridNdPrice = [
                            { id: "NDRound", name: "ID", field: "NDRound", width: 120, cssClass: "cell-title" },
                            { id: "ValidON", name: "ValidON", field: "ValidON" },
                            { id: "ValidTO", name: "ValidTO", field: "ValidTO", width: 80 },
                            { id: "remark", name: "remark", field: "remark", minWidth: 60 },
                           
                            {id: "ShowNDPrice", name: "", field:"NDRound", formatter:Slick.Formatters.ShowNDPrice}
                        ];
                        documentgrid = new Slick.Grid(gridtarget, datas , columnGridNdPrice, optionsDocumentGrid);
                        documentgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
                        documentgrid.onCellChange.subscribe(function (e, args) {
                            //updateUser(args.item);
                        });
                    });
                    
                }
                else {
                    datas = jQuery.grep(allDocument, function(n, i) {
                        return (n.Status === status);
                    });
                    documentgrid = new Slick.Grid(gridtarget, datas, columnGridDocument, optionsDocumentGrid);
                    documentgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
                    documentgrid.registerPlugin(checkboxSelector);
                    documentgrid.onCellChange.subscribe(function(e, args) {
                        //updateUser(args.item);
                    });
                }
            
            
            
                documentgrids[status] = documentgrid;
            
            }
            var documentgrids = {};
        
            var gridNDPrice;
            function getColumn(parameters) {
                var columnNDPriceGrid = [];
                columnNDPriceGrid.push({ id: 'mprodh_grpname', name: 'Product', field: 'mprodh_grpname'
                });
                columnNDPriceGrid.push({ id: 'NDPrice', name: 'NDPrice', field: 'discountPrice'
                });
                columnNDPriceGrid.push({
                    id: 'NDApproverLevel1', name: 'NDApproverLevel1', field: 'NDApproverLevel1',width:100
                });
                columnNDPriceGrid.push({
                    id: 'NDApproverLevel2', name: 'NDApproverLevel2', field: 'NDApproverLevel2', width: 100
                });
                columnNDPriceGrid.push({
                    id: 'NDApproverLevel3', name: 'NDApproverLevel3', field: 'NDApproverLevel3', width: 100
                });
                return columnNDPriceGrid;
            }
            var optionsNDprice = {
                editable: true,
                enableRowReordering: true,
                enableCellNavigation: true,
                asyncEditorLoading: false,
                autoEdit: false
            };
            var RoundID = -1 ;
            function showNdPriceDetail(roundID) {
                RoundID = roundID;
                helper.GetNDPriceByID( roundID, function(ndPricedata) {
                    var gridNDPrice = new Slick.Grid("#NDPriceGrid", ndPricedata.RMember, getColumn(), optionsNDprice);
                });
        
                var top = ($(window).height() - 250) / 2;
                var left = ($(window).width() - 350) / 2;
                $("#DivNdpriceDetails").dialog("open");
                $(".Dialog").css('left', left);
                $(".Dialog").css('top', top);
            }
            function sortJsonArrayByProp(objArray, prop){
                if (arguments.length<2){
                    throw new Error("sortJsonArrayByProp requires 2 arguments");
                }
                if (objArray.constructor===Array){
                    var propPath = (prop.constructor===Array) ? prop : prop.split(".");
                    objArray.sort(function(a,b){
           
                        if (a[propPath] && b[propPath]){
                            a = a[propPath];
                            b = b[propPath];
                        }
            
                        // convert numeric strings to integers
                        a = a.match(/^\d+$/) ? +a : a;
                        b = b.match(/^\d+$/) ? +b : b;
                        return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
                    });
                }   
            }
        </script>
    </head>
    <body>
        <div class="ui-layout-north ui-widget-content" style="display: none;">
            <div id="main_header">
                <div class="logo" style="float: left; margin-top: 10px;">
                    <img src="/images/logoNawa.png" alt="Nawaplastic Co.,Ltd." />
                </div>
                <div style="float: left; margin-top: 10px; margin-left: 100px;">
                    <span style="font-family: verdana; font-size: 16px; font-weight: bold;" class="ui-state-highlight"
                          id="curTime"></span>
                </div>
                <div style="float: right; margin-right: 160px;">
                    <div>
                        <div style="width: 70px; float: left">
                            User as:
                        </div>
                        <span class="userInfo" id="userNameShow">UserName</span><br />
                        <div style="width: 70px; float: left">
                            Logged in as:</div>
                        <span class="userInfo" id="SpanUserIP">IP</span>
                        <br />
                        <div style="width: 70px; float: left">
                            Role as :</div>
                        <span class="userInfo" id="SpanRoleShow">Role</span>
                    </div>
                </div>
            </div>
            <div id="toolbarHolder">
                <div class="ui-state-default ui-corner-all ui-helper-clearfix">
                    <ul id="main-menu" class="jd_menu dropdown ui-widget-header" onmouseover="myLayout.allowOverflow('north')"
                        onmouseout="myLayout.resetOverflow(this)">
                        <li><a href="#">Application &raquo;</a>
                            <ul class="ui-state-default">
                                <li><a href="/Page/AdminDocumentPage.htm">Admin Document Management</a></li>
                            </ul>
                        </li>
                        <li><a href="#">Admin Tools&raquo;</a>
                            <ul class="ui-state-default">
                                <li><a href="/Page/adminMain.htm">UserRole Management</a></li>
                                <li><a href="/Page/ndpriceManament.htm">ND Price Management</a></li>
                                <li><a href="/Page/SaleApprovalMapping.htm">Sale and Approver Mapping</a></li>
                                <li><a href="/Page/SaleCoordinatorMapping.htm">Sale and SaleCo Mapping</a></li>
                                <li><a href="/Page/ProductGrpManament.htm">Product Cate Management</a></li>
                                <li><a href="/Page/ApprovalManagement.htm">Approval Management</a></li>
                                <li><a target="blank" href="/Page/ReportViewer.aspx">Report</a></li>
                                <li><a target="blank" href="/Page/ImportPipePriceBath.aspx">Import Pipe price convert</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <div id="MessageBar" class="ui-layout-south ui-widget-content ui-state-error" style="display: none;">
            Message Bar
        </div>
        <div id="mainFrame" class="ui-layout-center" width="100%" height="600" frameborder="0"
             scrolling="auto">
        </div>
        <div id="DocumentListAdminStep" style="display: none">
            <div style="padding-top: 10px; padding-bottom: 30px; padding-left: 10px; padding-right: 10px;">
                <span style="float: left">Quick Search&nbsp;<input id="txtQuickFilterDoc" type="text"
                                                                   maxlength="50">
                                                            <button id="bthQuickSearchDoc">
                                                                Search</button>
                </span>
            </div>
            <div id="tabs" style="margin-left: 10px">
            </div>
            <button id="btnDeleteDoc" >
                Delete Document
            </button>
            <button id="btnExportSAP" style="display: none">
                Export To SAP
            </button>
            <button id="btnConfirmUploadedSAP" style="display: none">
                Confirm Uploaded To SAP
            </button>
        </div>
        <div id="DocumentDetailAdminStep" style="display: none">
            <div style="padding-top: 10px; padding-bottom: 30px; padding-left: 10px; padding-right: 10px;">
                <span id="Span1" class=" ui-corner-all" style="float: left">Valid On
                    <input id="txtValidOn" type="text" />
                    valid To
                    <input id="txtValidTo" type="text" />
                </span>
                <div class="ui-state-highlight" style="float: left; margin-left: 10px; font-size: large">
                    <span style="font-size: large" id="SpanDocIDCaption">Document ID: </span><span style="font-size: large"
                                                                                                   id="txtDocID"></span>
                </div>
                <span style="float: right">Sale Name:
                    <input id="txtSaleName" type="text" readonly="readonly" />
                    Sale Group:
                    <input id="txtSaleGroup" type="text" readonly="readonly" />
                </span>
            </div>
            <div style="margin-left: 5px; margin-bottom: 10px;">
                <button id="btnBackToDocList" style="float: left;">
                    Back To Document list</button>
                <div id="approveLevelDetails" style="float: left; display: none">
                    <span style="padding-left: 10px;" class="ui-widget-content">ต้องการ <span id="approvalDisplay"></span> อนุมัติ</span> 

                    <span style="padding-left: 10px;" class="highlightPriceApporver1">ต้องการ <span id="approvalDisplay1"></span> อนุมัติ</span>
                
                    <span style="padding-left: 10px;" class="highlightPriceApporver2">ต้องการ <span id="approvalDisplay2"></span> อนุมัติ</span>

                    <!--<span style="padding-left: 10px;" class="highlightPriceApporver3">ต้องการ <span id="approvalDisplay3"></span> อนุมัติ</span>

                        <span style="padding-left: 10px;" class="highlightPriceApporver3">ต้องการ <span id="approvalDisplay4"></span> อนุมัติ</span> -->
                    <span style="padding-left: 10px;" class="">Underline ราคาส่วนลดที่มากที่สุดในแต่ละรายการสินค้า</span>
                </div>
                <div style="clear: both">
                </div>
            </div>
            <div id="SaleCustomerDetailGrid" style="height: 270px;">
            </div>
            <div>
                <div style="margin: 5px; vertical-align: middle;">
                    <span style="width: 150px; display: inline-block;">Remark(สำหรับ sale & SC): </span>
                    <textarea id="remark" cols="5" rows="3" style="width: 400px;"></textarea>
                    <span id="realApprove" style="width: 60px;"></span>
                </div>
                <div style="margin: 5px; vertical-align: middle;">
                    <span style="width: 150px; display: inline-block;">Remark2(สำหรับ ผู้อนุมัติ): </span>
                    <textarea id="remark2" cols="5" rows="3" style="width: 400px;"></textarea></div>
                <div style="margin-top: 10px">
                    <button id="btnPrint" style="display: none">
                        Print</button>
                </div>
            </div>
            <div id="divButton" style="float: left; margin-left: 10px;">
                <!--<button id="btnEdit">
                        Edit</button>-->
                <button id="btnSave">
                    Save</button>
            </div>
        </div>
        <div class="ui-layout-west" style="display: none;">
            <h3 class="ui-widget-header">
                Navigation</h3>
            <div class="ui-layout-content">
                <div id="accordion1" class="basic">
                    <h3>
                        <a href="#">Section 1</a></h3>
                    <div>
                    </div>
                </div>
            </div>
        </div>
        <div id="loadingScreen">
        </div>
        <div id="DivNdpriceDetails" style="vertical-align: middle; text-align: center">
            <div id="NDPriceGrid" style="height: 300px; width:500px; margin-bottom: 20px; padding-left: 10px;">
            </div>
        </div>
        <div id="sapExportTextDownload" style="display: none">
            <div id="sapExportTextDownloadContent" style="margin: 10px;">
            
            </div>
        </div>
        <div id="sapExportNDTextDownload" style="display: none">
            <div id="sapExportNDTextDownloadContent" style="margin: 10px;">
            
            </div>
        </div>
        <div id="dialog-confirm" title="Please confirm delete the document." style="display:none">
            <p style="margin-top: 15px;">
                <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
                These data will be permanently deleted. Are you sure?</p>
        </div>
    </body>
</html>
